<template>
  <div class="song-outer">
    <!-- 搜索版块 -->
    <div class="search_box">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="名称">
          <el-input placeholder="歌手名或歌名" v-model="searchInfo" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button
            type="primary"
            @click="
              () => {
                searchInfo = '';
                set();
              }
            "
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="list_box_but1">
      <el-button
        type="primary"
        @click="
          dialogFormVisible = true;
          operate = 1;
        "
      >
        新增歌曲</el-button
      >
    </div>

    <div class="list_box1">
      <div class="list_table">
        <el-table
          size="small"
          :data="data"
          :height="tableHeight"
          @selection-change="handleSelectionChange"
          stripe
          :header-cell-style="{ background: '#EEF1F6' }"
        >
          <!-- <el-table-column type="selection" width="40"></el-table-column> -->
          <el-table-column
            label="ID"
            prop="id"
            align="center"
            width="50"
          ></el-table-column>
          <el-table-column label="歌手图片" width="100" align="center">
            <template v-slot="scope">
              <div style="width: 80px; height: 80px; overflow: hidden">
                <img
                  :src="getUrl(scope.row.songPic)"
                  style="width: 100%; object-fit: cover"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="歌名" prop="name"></el-table-column>
          <el-table-column label="专辑" prop="source"></el-table-column>
          <el-table-column label="歌曲文件" prop="songUrl" width="320">
            <template v-slot="scope">
              <audio
                v-if="scope.row.songUrl"
                :src="getUrl(scope.row.songUrl)"
                controls
                style="width: 320px"
              ></audio>
            </template>
          </el-table-column>
          <el-table-column label="歌词" align="center">
            <template v-slot="scope">
              <el-scrollbar height="100px">
                <ul>
                  <li
                    v-for="(item, index) in parseLyric(scope.row.lyric)"
                    :key="index"
                  >
                    {{ item }}
                  </li>
                </ul>
              </el-scrollbar>
            </template>
          </el-table-column>
          <el-table-column label="资源更新" width="120" align="center">
            <template v-slot="scope">
              <el-upload
                ref="uploadRef"
                class="upload"
                :action="getUrl('/mv/upload')"
                :data="{ type: 'song' }"
                :auto-upload="true"
                :show-file-list="false"
                :on-success="(response:any) => updateInfo(response, scope.row.id)"
              >
                <el-button>更新图片</el-button>
              </el-upload>
              <br />
              <el-upload
                ref="uploadRef"
                class="upload"
                :action="getUrl('/mv/upload')"
                :data="{ type: 'songAudio' }"
                :auto-upload="true"
                :show-file-list="false"
                :on-success="(response:any) => updateAudio(response, scope.row.id)"
                :before-upload="beforeUpload"
              >
                <el-button>更新歌曲</el-button>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" align="center">
            <template v-slot="scope">
              <el-button @click="editRow(scope.row)">编辑</el-button>
              <el-popconfirm
                title="删除不可恢复，是否确定删除?"
                @confirm="deleteRow(scope.row.id)"
              >
                <template #reference>
                  <el-button type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="list_pagination">
      <el-pagination
        class="pagination"
        background
        layout="total, prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
    <!-- 内容版块 -->

    <el-dialog
      v-model="dialogFormVisible"
      :title="operate ? '新增歌曲' : '修改歌曲'"
      width="500"
      center
      :destroy-on-close="true"
      @close="clearInfo"
    >
      <el-form
        ref="formRef"
        :model="infoForm"
        :hide-required-asterisk="true"
        label-width="80"
      >
        <el-form-item
          prop="singerId"
          label="歌手"
          :rules="{
            required: true,
            message: '请选择歌手',
            trigger: 'change',
          }"
        >
          <el-select
            v-model="infoForm.singerId"
            placeholder="请选择歌手"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in singerList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          prop="name"
          label="歌曲名"
          :rules="{
            required: true,
            message: '歌曲不能为空',
            trigger: 'blur',
          }"
        >
          <el-input v-model="infoForm.name" placeholder="输入歌曲名" />
        </el-form-item>
        <el-form-item
          prop="source"
          label="专辑"
          :rules="{
            required: true,
            message: '详情不能为空',
            trigger: 'blur',
          }"
        >
          <el-input v-model="infoForm.source" placeholder="输入专辑名称" />
        </el-form-item>
        <el-form-item
          prop="lyric"
          label="歌词"
          :rules="{
            required: true,
            message: '歌词不能为空',
            trigger: 'blur',
          }"
        >
          <el-input
            v-model="infoForm.lyric"
            placeholder="输入歌词"
            :rows="10"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submit(formRef)"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { getSongs, addSongs, updateSongs, getAllSinger, delSongs } from "@/api";
import { getUrl } from "@/utils copy/format";
import type { FormInstance } from "element-plus";

const formRef = ref<FormInstance>();
const tableData = ref([]); // 记录歌曲，用于显示
const currentPage = ref(1);
const pageSize = ref(10);
const multipleSelection = ref([]); // 记录当前要删除的列表
const data = ref([]);
const tableHeight = ref(0);
const searchInfo = ref("");
tableHeight.value = window.innerHeight - 205;
const operate = ref(1);
const dialogFormVisible = ref(false);
let operateId: number;
let singerList = [];
let duration = 0;
const infoForm = ref({
  singerId: "",
  name: "",
  source: "",
  lyric: "",
  songUrl: "",
});
const clearInfo = () => {
  infoForm.value = {
    name: "",
    source: "",
    lyric: "",
    songUrl: "",
  };
};
async function deleteRow(id: number) {
  await delSongs(id);
  set();
}
// 获取时长
function beforeUpload(file: any) {
  let url = URL.createObjectURL(file);
  var audioElement = new Audio(url);
  audioElement.addEventListener("loadedmetadata", function () {
    duration = Math.ceil(audioElement.duration);
  });
}
const editRow = (row: any) => {
  operate.value = 0;
  infoForm.value = row;
  operateId = row.id;
  dialogFormVisible.value = true;
};
async function updateInfo(response: any, id: number) {
  await updateSongs({ id, songPic: response.data });
  set();
}
async function updateAudio(response: any, id: number) {
  await updateSongs({ id, songUrl: response.data, duration });
  set();
  duration = 0;
}
getSinger();
async function getSinger() {
  singerList = await getAllSinger("");
}
const submit = (formEl: any) => {
  if (!formEl) return;
  formEl.validate(async (valid: any) => {
    if (valid) {
      let res: any;
      if (operate.value) {
        res = await addSongs({
          ...infoForm.value,
          name: concatSonfName(),
        });
      } else {
        res = await updateSongs({ ...infoForm.value, id: operateId });
      }
      console.log(res);
      set();
      dialogFormVisible.value = false;
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
const handleCurrentChange = (val: any) => {
  currentPage.value = val;
  console.log(`current page: ${val}`);
  getData();
};
function concatSonfName() {
  const list = singerList.filter((item) => item.id == infoForm.value.singerId);
  return `${list[0].name}-${infoForm.value.name}`;
}
async function handleSearch() {
  currentPage.value = 1;
  tableData.value = data.value = await getSongs(searchInfo.value.trim());
}
function getData() {
  data.value = tableData.value.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  );
}
function handleSelectionChange(val: any) {
  multipleSelection.value = val;
}
function parseLyric(text) {
  const lines = text.split("\n");
  const pattern = /\[\d{2}:\d{2}.(\d{3}|\d{2})\]/g;
  const result = [];

  // 对于歌词格式不对的特殊处理
  if (!/\[.+\]/.test(text)) {
    return [text];
  }
  for (const item of lines) {
    if (pattern.test(item)) {
      const value = item.replace(pattern, ""); // 存歌词
      result.push(value);
    }
  }
  return result;
}
async function set() {
  currentPage.value = 1;
  tableData.value = [];
  const singers = await getSongs();
  tableData.value = singers;
  getData();
}
onMounted(() => {
  set();
});
</script>

<style lang="scss" scoped>
@import "@/static/css/common.scss";

svg {
  width: 14px;
  height: 14px;
  fill: #fff;
  margin-right: 4px;
}

:deep(.el-table__cell) {
  border-bottom: none !important;
}

.inner_icon {
  fill: #4d70ff;
  margin-right: 2px;
}

.inner_icon:hover {
  fill: #2d56fa;
}

.song-outer {
  padding-bottom: 10px;
}

.list_box1 {
  text-indent: 0;
  background: #fff;
  border-radius: 4px;
  overflow: auto;
}
.list_box_but,
.list_table {
  width: 98%;
  margin: 0 auto;
  margin-top: 10px;
}
.list_box_but1 {
  position: absolute;
  top: 18px;
  right: 30px;
}
.list_box_but a {
  color: #fff;
}
.list_pagination {
  //padding-top: 14px;
  text-indent: 0;
  > div {
    justify-content: flex-end;
    margin-right: 20px;
  }
}
</style>
